package io.geekidea.boot.util.dingtalk;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson2.JSON;
import com.aliyun.dingtalkdrive_1_0.models.AddSpaceHeaders;
import com.aliyun.dingtalkdrive_1_0.models.AddSpaceRequest;
import com.aliyun.dingtalkdrive_1_0.models.AddSpaceResponse;
import com.aliyun.dingtalkdrive_1_0.models.AddSpaceResponseBody;
import com.aliyun.dingtalkdrive_1_0.models.ListSpacesHeaders;
import com.aliyun.dingtalkdrive_1_0.models.ListSpacesRequest;
import com.aliyun.dingtalkdrive_1_0.models.ListSpacesResponse;
import com.aliyun.dingtalkdrive_1_0.models.ListSpacesResponseBody.ListSpacesResponseBodySpaces;
import com.aliyun.dingtalkstorage_1_0.models.GetSpaceResponse;
import com.aliyun.dingtalkstorage_1_0.models.GetSpaceResponseBody.GetSpaceResponseBodySpace;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class DingSpaceUtil {

  /**
   * 使用 Token 初始化账号Client
   *
   * @return Client
   * @throws Exception
   */
  private static com.aliyun.dingtalkdrive_1_0.Client createClient() throws Exception {
    Config config = new Config();
    config.protocol = "https";
    config.regionId = "central";
    return new com.aliyun.dingtalkdrive_1_0.Client(config);
  }

  /**
   * https://open.dingtalk.com/document/orgapp/new-space
   *
   * @param accessToken
   * @param name
   * @param unionId
   * @return
   */
  public static AddSpaceResponseBody NewSpace(String accessToken, String name, String unionId) {
    com.aliyun.dingtalkdrive_1_0.Client client = null;
    try {
      client = DingSpaceUtil.createClient();
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
      return null;
    }

    AddSpaceHeaders addSpaceHeaders = new AddSpaceHeaders();
    addSpaceHeaders.xAcsDingtalkAccessToken = accessToken;
    AddSpaceRequest addSpaceRequest = new AddSpaceRequest()
        .setName(StringUtils.trim(name))
        .setUnionId(unionId);
    try {
      AddSpaceResponse resp = client.addSpaceWithOptions(addSpaceRequest, addSpaceHeaders,
          new RuntimeOptions());
      if (resp.getStatusCode() == HttpStatus.HTTP_OK) {
        return resp.getBody();
      }
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
    }
    return null;
  }

  /**
   * https://open.dingtalk.com/document/orgapp/queries-a-space-list
   *
   * @param accessToken
   * @param unionId
   * @return
   */
  public static List<ListSpacesResponseBodySpaces> spaceList(String accessToken, String unionId,
      String nextToken) {

    com.aliyun.dingtalkdrive_1_0.Client client = null;
    try {
      client = DingSpaceUtil.createClient();
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
      return null;
    }
    ListSpacesHeaders listSpacesHeaders = new ListSpacesHeaders();
    listSpacesHeaders.xAcsDingtalkAccessToken = accessToken;
    ListSpacesRequest listSpacesRequest = new ListSpacesRequest()
        .setUnionId(unionId)
        .setSpaceType("org")
        .setMaxResults(50);

    if (StringUtils.isNotBlank(nextToken)) {
      listSpacesRequest.setNextToken(nextToken);
    }

    try {
      ListSpacesResponse resp = client.listSpacesWithOptions(listSpacesRequest, listSpacesHeaders,
          new RuntimeOptions());

      List<ListSpacesResponseBodySpaces> result = new ArrayList<>();
      if (resp.getStatusCode() == HttpStatus.HTTP_OK) {
        log.debug("spaceList 返回信息：{}", JSON.toJSONString(resp));
        if (resp.getBody() != null && !resp.getBody().getSpaces().isEmpty()) {
          result.addAll(resp.getBody().getSpaces());
        }
        if (StringUtils.isNotBlank(resp.getBody().getNextToken())) {
          List<ListSpacesResponseBodySpaces> listSpacesResponseBodySpaces = spaceList(accessToken,
              unionId, resp.getBody().getNextToken());
          if (listSpacesResponseBodySpaces != null) {
            result.addAll(listSpacesResponseBodySpaces);
          }
        }
      }
      return result;
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
    }
    return null;
  }

  /**
   * https://open.dingtalk.com/document/orgapp/get-space-information
   *
   * @param accessToken
   * @param spaceId
   * @param unionId
   * @return
   */
  public static GetSpaceResponseBodySpace spaceDetail(String accessToken, String spaceId,
      String unionId) {

    com.aliyun.dingtalkstorage_1_0.Client client = null;
    try {
      com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
      config.protocol = "https";
      config.regionId = "central";
      client = new com.aliyun.dingtalkstorage_1_0.Client(config);
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
      return null;
    }
    com.aliyun.dingtalkstorage_1_0.models.GetSpaceHeaders getSpaceHeaders = new com.aliyun.dingtalkstorage_1_0.models.GetSpaceHeaders();
    getSpaceHeaders.xAcsDingtalkAccessToken = accessToken;
    com.aliyun.dingtalkstorage_1_0.models.GetSpaceRequest getSpaceRequest = new com.aliyun.dingtalkstorage_1_0.models.GetSpaceRequest()
        .setUnionId(unionId);
    try {
      GetSpaceResponse resp = client.getSpaceWithOptions(spaceId, getSpaceRequest,
          getSpaceHeaders,
          new com.aliyun.teautil.models.RuntimeOptions());
      if (resp.getStatusCode() == HttpStatus.HTTP_OK && resp.getBody() != null
          && resp.getBody().getSpace() != null) {
        log.debug("spaceDetail 返回信息：{}", resp.getBody());
        return resp.getBody().getSpace();
      }

    } catch (Exception e) {
      log.error("空间：{} 操作员 {} 错误消息：{}", spaceId, unionId, e.getMessage(), e);
    }
    return null;
  }
}
